# Identify home location with respect to responsibility and fire hazard (in SRA, Moderate, High, or Very High)
# Responsibility can be SRA, LRA, or FRA
# Fire hazard in SRA can be Moderate, High, or Very High
# Fire hazard in LRA can only be Very High (or not rated)

pacman::p_load(tidyverse, sf, cowplot, data.table, mapview, modelsummary, fst, qs)

# Setup
rm(list = ls())

source("code/globals.R") # Has the relevant function get_SRA_FSHZ_status

# Load home points for at-risk sample
homepoints <- qread(file.path(WORKING, "homepoints.qs")) %>%
  rename(incidentid = UNIT_AND_NUMBER)

# Get year built
yearbuilt <- qread(file.path(WORKING, "maindata.qs")) %>%
  select(ImportParcelID, BuildingOrImprovementNumber, incidentid, combinedyear)

homepoints <- homepoints %>% inner_join(yearbuilt)

# Get status -----

homepoints <- get_SRA_FHSZ_status(homepoints)

# Assign regime
# Follow original regime definition: SRA/FRA designation from SRA, LRA-VH designation from either 98/08
homepoints <- homepoints %>%
  mutate(regime = case_when(
    incidentid %in% c("Black Forest_8041_2013", "CameronPeakFire_8069_2020", "HighparkFire_8069_2012", "MM 117 Fire_8041_2018", "Waldo Canyon_8041_2012")  ~ "localcodes",
    State != "California" ~ "otherstates",
    SRA == "SRA" ~ "sra",
    SRA == "FRA" ~ "fra",
    SRA != "SRA" & hazclass_lra_98 == "Very High" & hazclass_lra_08 == "Very High" ~ "lraYY",
    SRA != "SRA" & hazclass_lra_98 != "Very High" & hazclass_lra_08 == "Very High" ~ "lraNY",
    SRA != "SRA" & hazclass_lra_98 != "Very High" & hazclass_lra_08 != "Very High" ~ "lraNN",
    SRA != "SRA" & hazclass_lra_98 == "Very High" & hazclass_lra_08 != "Very High" ~ "lraYN",
  ))

# Save without geometry
write_fst(homepoints %>% st_drop_geometry(), file.path(WORKING, "sra.fst"))

